package com.demo2do.boyle.backend.web.controller.aduser;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.boyle.backend.service.aduser.AduserService;
import com.demo2do.boyle.common.entity.AuditStatus;
import com.demo2do.boyle.common.entity.aduser.Aduser;
import com.demo2do.core.entity.Result;
import com.demo2do.core.persistence.support.Filter;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Page;

/** 
 * @author mohanlan leo
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-aduser")
public class AduserAuditController {
	
	@Autowired
	private AduserService aduserService;
	
	/**
	 * @return the audit aduser list
	 */
	@RequestMapping("/aduser-audits")
	@MenuSetting("submenu-aduser-audit")
	public ModelAndView list(Page page) {
		
		ModelAndView modelAndView = new ModelAndView("aduser/audit/aduser-audit-list");		
		
		Filter filter = new Filter().addEquals("disabled", false)
                					.addEquals("status", AuditStatus.AUDITING);
		
		List<Aduser> adusers = aduserService.list(Aduser.class, filter, page);
		
		modelAndView.addObject("adusers", adusers);
		
		return modelAndView;
	}
	
	
	/**
	 * @param id
	 * @return the audit view
	 */
    @RequestMapping("/aduser-audits/{id}")
    @MenuSetting("submenu-aduser-audit")
	public ModelAndView view(@PathVariable("id") Integer id) {
		ModelAndView modelAndView = new ModelAndView("aduser/audit/aduser-audit-view");
		Aduser aduser = aduserService.load(Aduser.class, id);
		modelAndView.addObject("aduser", aduser);
		return modelAndView;
	}
    
    /**
     * @param id
     * @return the view to confirm the submit
     */
    @RequestMapping("/adusers/{id}/audit")
    public ModelAndView audit(@PathVariable("id") Integer id) {
    	ModelAndView modelAndView = new ModelAndView("aduser/audit/aduser-audit");
		modelAndView.addObject("id", id);
		return modelAndView;
    }
    
    /**
     * @param id
     * @return the audit result with message
     */
    @RequestMapping(value ="/adusers/{id}/audit", method = RequestMethod.PATCH )
    public @ResponseBody String onAudit(@PathVariable("id") int id) {
    	Result result = new Result();
    	try{
    		Aduser aduser = aduserService.load(Aduser.class, id);
        	aduser.setStatus(AuditStatus.AUDITED);
        	aduserService.update(aduser);
        	result.success().message("审核成功");
    	}catch(Exception e){
    		result.fail().message("审核失败");
    	}
    	return JsonUtils.toJsonString(result);
    }

}
